<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>145_联系_选择框_change事件</title>
		<script>
			/* 全选功能
				取消
				反选
				提交
			 */
			window.onload = function() {
				const hobbies = document.getElementsByName("hobby");

				const checkAllBox = document.getElementById("check-all")
				const allBtn = document.getElementById("all");
				const noBtn = document.getElementById("no")
				const reverseBtn = document.getElementById("reverse");
				const submitBtn = document.getElementById("submit")


				/*  check-all
					全选checkbox发生变化后，将小的checkbox和它同步;
				 */
				//input选中和不选中事件
				checkAllBox.onchange = function() {

				}
				checkAllBox.addEventListener("change", function() {
					// checkAllBox.addEventListener("change", () => {
					for (let i = 0; i < hobbies.length; i++) {
						console.log(this) //this就是checkAllBox,如果是箭头函数，this是Windows
						//在事件的响应函数中，响应函数绑定给谁 this就是谁(箭头函数除外，箭头函数要
						//看它的外部域)

						//不用这样写
						//hobbies[i].checked = !hobbies[i].checked; 
						//如果是普通函数，这里可以这样写this.checked
						hobbies[i].checked = checkAllBox.checked;
					}
				})


				/* 
					使全选checkbox和四个checkbox进行同步
						如果四个全选了，则全选checkbox也选中
						如果四个没全选，则全选checkbox也不选中
				 */

				allBtn.onclick = function() {
					for (let i = 0; i < hobbies.length; i++) {
						hobbies[i].checked = true;
					}
				}

				noBtn.onclick = function() {
					for (let i = 0; i < hobbies.length; i++) {
						hobbies[i].checked = false;
					}
				}

				reverseBtn.onclick = function() {
					for (let i = 0; i < hobbies.length; i++) {
						hobbies[i].checked = !hobbies[i].checked;
					}
				}

				submitBtn.onclick = function() {
					let seletStr = "";
					for (let i = 0; i < hobbies.length; i++) {
						if (hobbies[i].checked)
							seletStr = seletStr + hobbies[i].value
					}
					console.log("您的爱好是", seletStr);
				}

				for (let i = 0; i < hobbies.length; i++) {
					hobbies[i].onchange = function() {
						//获取所有选中的checkbox
						//通过属性选择器查找所有name=hobby的标签
						//const checkedBox = document.querySelectorAll("[name=hobby]") 
						//使用伪类选择器
						const checkedBox = document.querySelectorAll("[name=hobby]:checked")
						console.log(checkedBox.length);

						//判断hobbies是否全选
						if (hobbies.length === checkedBox.length) {
							checkAllBox.checked = true;
						} else {
							checkAllBox.checked = false;
						}
					}
				}
			}
		</script>
	</head>
	<body>
		<div>
			<form action="#">
				请选择你的兴趣爱好<input id="check-all" type="checkbox" />全选
				<div>
					<input type="checkbox" name="hobby" value="乒乓球" />乒乓球
					<input type="checkbox" name="hobby" value="篮球" />篮球
					<input type="checkbox" name="hobby" value="羽毛球" />羽毛球
					<input type="checkbox" name="hobby" value="足球" />足球
				</div>
				<div>
					<button type="button" id="all">全选</button>
					<button type="button" id="no">取消</button>
					<button type="button" id="reverse">反选</button>
					<button type="button" id="submit">提交</button>
				</div>
			</form>
		</div>
	</body>
</html>